from CvPythonExtensions import *
from WriterUtils import *

import CvScreenEnums
import CvUtil
import CvConfigParser
import CvPath
import os
import os.path
import Popup as PyPopup
import shutil 

# globals
gc = CyGlobalContext()
ArtFileMgr = CyArtFileMgr()
localText = CyTranslator()

# Change this to change the location where the resulting CIV4BonusInfos.xml file 
# will be saved. So if the default value is left to "Test" then the 
# CIV4BonusInfos.xml file would be written in a directory called "Test" inside 
# of the Tech Tree Editor mod folder.
# Default value is Test
g_strSaveDirectoryLocation = "Test"

# Change the value to false if the assets directory structure shouldn't be 
# created at the directory specified by the "Save Directory Location".
# Default value is True
g_bCreateAssetHierarchy = True

# Change the value to false if the changes made shouldn't be saved into the 
# assets directory for the tech editor. Changing it to false will require 
# manual copying of the saved files from the directory specified in the 
# "Save Directory Location" configurable option to the editor's asset directory 
# when wanting to edit existing mod files.
# Default value is True
g_bSaveChangesInEditorAssetsDirectory = True

def loadConfigurationValues():
	global g_strSaveDirectoryLocation
	global g_bCreateAssetHierarchy
	global g_bSaveChangesInEditorAssetsDirectory
	
	config = CvConfigParser.CvConfigParser("ViSa_v3.ini")

	if(config != None):
		g_strSaveDirectoryLocation = config.get("Tech Tree Editor", "Save Directory Location", "Test")
		g_bCreateAssetHierarchy = config.getboolean("Tech Tree Editor", "Create Asset Hierarchy", True)
		g_bSaveChangesInEditorAssetsDirectory = config.getboolean("Tech Tree Editor", "Save Changes In Editor Assets Directory", True)

		if(len(g_strSaveDirectoryLocation) == 0):
			g_strSaveDirectoryLocation = "Test"
			
class BonusInfoWriter:
		
	def __init__(self):
		loadConfigurationValues()

	def isYieldChangesDefined(self, iBonus):		
		objBonusInfo = gc.getBonusInfo(iBonus)

		for iI in range(YieldTypes.NUM_YIELD_TYPES):
			if(objBonusInfo.getYieldChange(iI) != 0):
				return true
		return false

	def isTerrainBooleansDefined(self, iBonus):
		objBonusInfo = gc.getBonusInfo(iBonus)
			
		for iI in range(gc.getNumTerrainInfos()):
			if(objBonusInfo.isTerrain(iI)):
				return true
				
		return false

	def isFeatureBooleansDefined(self, iBonus):
		objBonusInfo = gc.getBonusInfo(iBonus)
			
		for iI in range(gc.getNumFeatureInfos()):
			if(objBonusInfo.isFeature(iI)):
				return true
				
		return false

	def isFeatureTerrainBooleansDefined(self, iBonus):
		objBonusInfo = gc.getBonusInfo(iBonus)
			
		for iI in range(gc.getNumTerrainInfos()):
			if(objBonusInfo.isFeatureTerrain(iI)):
				return true
				
		return false
		
	def printBonus(self, iBonus):
		
		objBonusInfo = gc.getBonusInfo(iBonus)

		szText = ""
		
		szText = appendString(szText,"		<BonusInfo>")
		
		szText = appendString(szText,"			<Type>%s</Type>" %(objBonusInfo.getType()))
		szText = appendString(szText,"			<Description>%s</Description>" %(objBonusInfo.getTextKey()))
		szText = appendString(szText,"			<Civilopedia>%s</Civilopedia>" %(objBonusInfo.getCivilopediaKey()))
		if(objBonusInfo.getBonusClassType() == 0):
			szText = appendString(szText,"			<BonusClassType>BONUSCLASS_GENERAL</BonusClassType>")
		else:
			szText = appendString(szText,"			<BonusClassType>%s</BonusClassType>" %(gc.getBonusClassInfo(objBonusInfo.getBonusClassType()).getType()))
		szText = appendString(szText,"			<ArtDefineTag>%s</ArtDefineTag>" %(objBonusInfo.getArtDefineTag()))

		if(objBonusInfo.getTechReveal() != -1):
			szText = appendString(szText,"			<TechReveal>%s</TechReveal>" %(gc.getTechInfo(objBonusInfo.getTechReveal()).getType()))
		else:
			szText = appendString(szText,"			<TechReveal>NONE</TechReveal>")

		if(objBonusInfo.getTechCityTrade() != -1):
			szText = appendString(szText,"			<TechCityTrade>%s</TechCityTrade>" %(gc.getTechInfo(objBonusInfo.getTechCityTrade()).getType()))
		else:
			szText = appendString(szText,"			<TechCityTrade>NONE</TechCityTrade>")
		
		if(objBonusInfo.getTechObsolete() != -1):
			szText = appendString(szText,"			<TechObsolete>%s</TechObsolete>" %(gc.getTechInfo(objBonusInfo.getTechObsolete()).getType()))
		else:
			szText = appendString(szText,"			<TechObsolete>NONE</TechObsolete>")

		if(self.isYieldChangesDefined(iBonus)):
			szText = appendString(szText,"			<YieldChanges>")
			for iI in range(YieldTypes.NUM_YIELD_TYPES):
				szText = appendString(szText,"				<iYieldChange>%s</iYieldChange>" %(objBonusInfo.getYieldChange(iI)))
			szText = appendString(szText,"			</YieldChanges>")
		else:
			szText = appendString(szText,"			<YieldChanges/>")

		szText = appendString(szText,"			<iAITradeModifier>%s</iAITradeModifier>" %(objBonusInfo.getAITradeModifier()))
		szText = appendString(szText,"			<iAIObjective>%s</iAIObjective>" %(objBonusInfo.getAIObjective()))
		szText = appendString(szText,"			<iHealth>%s</iHealth>" %(objBonusInfo.getHealth()))
		szText = appendString(szText,"			<iHappiness>%s</iHappiness>" %(objBonusInfo.getHappiness()))
		szText = appendString(szText,"			<iPlacementOrder>%s</iPlacementOrder>" %(objBonusInfo.getPlacementOrder()))
		szText = appendString(szText,"			<iConstAppearance>%s</iConstAppearance>" %(objBonusInfo.getConstAppearance()))
		szText = appendString(szText,"			<iMinAreaSize>%s</iMinAreaSize>" %(objBonusInfo.getMinAreaSize()))
		szText = appendString(szText,"			<iMinLatitude>%s</iMinLatitude>" %(objBonusInfo.getMinLatitude()))
		szText = appendString(szText,"			<iMaxLatitude>%s</iMaxLatitude>" %(objBonusInfo.getMaxLatitude()))

		szText = appendString(szText,"			<Rands>")
		szText = appendString(szText,"				<iRandApp1>%s</iRandApp1>" %(objBonusInfo.getRandAppearance1()))
		szText = appendString(szText,"				<iRandApp2>%s</iRandApp2>" %(objBonusInfo.getRandAppearance2()))
		szText = appendString(szText,"				<iRandApp3>%s</iRandApp3>" %(objBonusInfo.getRandAppearance3()))
		szText = appendString(szText,"				<iRandApp4>%s</iRandApp4>" %(objBonusInfo.getRandAppearance4()))
		szText = appendString(szText,"			</Rands>")
		
		szText = appendString(szText,"			<iPlayer>%s</iPlayer>" %(objBonusInfo.getPercentPerPlayer()))
		szText = appendString(szText,"			<iTilesPer>%s</iTilesPer>" %(objBonusInfo.getTilesPer()))
		szText = appendString(szText,"			<iMinLandPercent>%s</iMinLandPercent>" %(objBonusInfo.getMinLandPercent()))
		szText = appendString(szText,"			<iUnique>%s</iUnique>" %(objBonusInfo.getUniqueRange()))
		szText = appendString(szText,"			<iGroupRange>%s</iGroupRange>" %(objBonusInfo.getGroupRange()))
		szText = appendString(szText,"			<iGroupRand>%s</iGroupRand>" %(objBonusInfo.getGroupRand()))

		szText = appendString(szText,"			<bArea>%s</bArea>" %(boolToInt(objBonusInfo.isOneArea())))
		szText = appendString(szText,"			<bHills>%s</bHills>" %(boolToInt(objBonusInfo.isHills())))
		szText = appendString(szText,"			<bFlatlands>%s</bFlatlands>" %(boolToInt(objBonusInfo.isFlatlands())))
		szText = appendString(szText,"			<bNoRiverSide>%s</bNoRiverSide>" %(boolToInt(objBonusInfo.isNoRiverSide())))
		szText = appendString(szText,"			<bNormalize>%s</bNormalize>" %(boolToInt(objBonusInfo.isNormalize())))
		
		if(self.isTerrainBooleansDefined(iBonus)):
			szText = appendString(szText,"			<TerrainBooleans>")
			for iI in range(gc.getNumTerrainInfos()):
				if(objBonusInfo.isTerrain(iI)):
					szText = appendString(szText,"				<TerrainBoolean>")
					szText = appendString(szText,"					<TerrainType>%s</TerrainType>" %(gc.getTerrainInfo(iI).getType()))
					szText = appendString(szText,"					<bTerrain>%s</bTerrain>" %(boolToInt(objBonusInfo.isTerrain(iI))))
					szText = appendString(szText,"				</TerrainBoolean>")
			szText = appendString(szText,"			</TerrainBooleans>")
		else:
			szText = appendString(szText,"			<TerrainBooleans/>")

		if(self.isFeatureBooleansDefined(iBonus)):
			szText = appendString(szText,"			<FeatureBooleans>")
			for iI in range(gc.getNumFeatureInfos()):
				if(objBonusInfo.isFeature(iI)):
					szText = appendString(szText,"				<FeatureBoolean>")
					szText = appendString(szText,"					<FeatureType>%s</FeatureType>" %(gc.getFeatureInfo(iI).getType()))
					szText = appendString(szText,"					<bFeature>%s</bFeature>" %(boolToInt(objBonusInfo.isFeature(iI))))
					szText = appendString(szText,"				</FeatureBoolean>")
			szText = appendString(szText,"			</FeatureBooleans>")
		else:
			szText = appendString(szText,"			<FeatureBooleans/>")		
		
		if(self.isFeatureTerrainBooleansDefined(iBonus)):
			szText = appendString(szText,"			<FeatureTerrainBooleans>")
			for iI in range(gc.getNumTerrainInfos()):
				if(objBonusInfo.isFeatureTerrain(iI)):
					szText = appendString(szText,"				<FeatureTerrainBoolean>")
					szText = appendString(szText,"					<TerrainType>%s</TerrainType>" %(gc.getTerrainInfo(iI).getType()))
					szText = appendString(szText,"					<bFeatureTerrain>%s</bFeatureTerrain>" %(boolToInt(objBonusInfo.isFeatureTerrain(iI))))
					szText = appendString(szText,"				</FeatureTerrainBoolean>")
			szText = appendString(szText,"			</FeatureTerrainBooleans>")
		else:
			szText = appendString(szText,"			<FeatureTerrainBooleans/>")

		if(objBonusInfo.useLSystem()):
			szText = appendString(szText,"			<bUseLSystem>%s</bUseLSystem>" %(boolToInt(objBonusInfo.useLSystem())))
			
			
		szText = appendString(szText,"		</BonusInfo>")
			
		return szText

						
	def printBonuss(self):	
	
		strSavePath = ""
		strFileSavePath = ""
		strModPath = ""
		strModAssetPath = ""
		strModAssetSavePath = ""
		strModAssetPath = ""
		
		if(os.access(CvPath.userActiveModDir,os.F_OK)):
			strModPath = CvPath.userActiveModDir
		elif(os.access(CvPath.installActiveModDir,os.F_OK)):
			strModPath = CvPath.installActiveModDir
		else:
			self.dataSavePopup(false)
			return
			
		strSavePath = "%s\%s" %(strModPath,g_strSaveDirectoryLocation)
		strModAssetPath = "%s\\Assets\\" %(strModPath)
		
		if(g_bCreateAssetHierarchy):
			strSavePath += "\Assets\XML\Terrain" 

		strFileSavePath = "%s\%s" %(strSavePath, "CIV4BonusInfos.xml")

		try:
			if(os.access(strSavePath,os.F_OK)):
				if(os.access(strFileSavePath,os.F_OK)):
					os.remove(strFileSavePath)
				os.removedirs(strSavePath)
		except:
			pass
			
		if(not os.access(strSavePath,os.F_OK)):
			os.makedirs(strSavePath)

							
		szText = "<?xml version=\"1.0\"?>"
		szText = appendString(szText,"<!-- Created by Tech Civilizeditor %s by TheLopez-->" %(editorVersion()))
		szText = appendString(szText,"<!-- Sid Meier's Civilization 4 -->")
		szText = appendString(szText,"<!-- Copyright Firaxis Games 2005 -->")
		szText = appendString(szText,"<!-- -->")
		szText = appendString(szText,"<!-- Bonus Infos -->")
		szText = appendString(szText,"<!-- WARNING: It is not recommended that you remove Bonuses due to complications with the LSystem -->")

		szText = appendString(szText,"<Civ4BonusInfos xmlns=\"x-schema:CIV4TerrainSchema.xml\">")
		szText = appendString(szText,"	<BonusInfos>")
				
		for iBonus in range(gc.getNumBonusInfos()):

			if(gc.getBonusInfo(iBonus).isDeleted()):
				continue

			szText = appendString(szText,self.printBonus(iBonus))
			
						
		szText = appendString(szText,"	</BonusInfos>")
		szText = appendString(szText,"</Civ4BonusInfos>")

			
		fd = os.open(strFileSavePath, os.O_CREAT)
		os.close(fd)

		fd = os.open(strFileSavePath, os.O_RDWR)
		os.write(fd, szText)
		os.close(fd)
		
		if(g_bSaveChangesInEditorAssetsDirectory):
			strModAssetPath = "%s\%s" %(strModPath,"\Assets\XML\Terrain")
			strModAssetSavePath = "%s\%s" %(strModPath, "\Assets\XML\Terrain\CIV4BonusInfos.xml")
			try:
				if(os.access(strModAssetPath,os.F_OK)):
					if(os.access(strModAssetSavePath,os.F_OK)):
						os.remove(strModAssetSavePath)
			except:
				pass
			
			if(not os.access(strModAssetPath,os.F_OK)):
				os.makedirs(strModAssetPath)

			fd = os.open(strModAssetSavePath, os.O_CREAT)
			os.close(fd)

			fd = os.open(strModAssetSavePath, os.O_RDWR)
			os.write(fd, szText)
			os.close(fd)
	

